package com.haiyi.activiti.engine.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p> </p>
 *
 * <pre> Created: 2018/12/15 11:01 </pre>
 *
 * @author hlu
 * @version 1.0
 * @since JDK 1.7
 */
@Configuration
public class FastjsonConfig {

    /**
     * 对 JSON中的字段类型处理，避免LONG型转换到客户端出现溢出的问题
     */
    private static final ValueFilter JSON_VALUE_FILTER = new ValueFilter() {
        @Override
        public Object process(Object o, String s, Object o1) {
            if (o1 instanceof Long) {
                return o1.toString();
            }
            return o1;
        }
    };

    @Bean
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        // @see https://my.oschina.net/u/2474629/blog/748752
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse,
                // 关闭 fastjson的循环引用
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.BrowserCompatible
        );
        fastJsonConfig.setSerializeFilters(JSON_VALUE_FILTER);
        converter.setFastJsonConfig(fastJsonConfig);
        return converter;
    }
}
